<?php

namespace App\Modules\Common;


use App\Library\Rank\AbstractSingleRank;
use App\Modules\Rebate\Models\Rebate;
use App\Modules\User\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Redis;

class PartnerRebateRank extends AbstractSingleRank
{
    protected static $key = "partner:rebate_ranking";

    public static function setKey($prefix)
    {
        self::$key = "partner:rebate_ranking:{$prefix}";
    }

    public static function increaseAll($id, $step = 1)
    {
        self::setKey('quarterly');
        self::increase($id, $step);

        self::setKey('annual');
        self::increase($id, $step);

        self::setKey('previous');
        self::increase($id, $step);

        for ($i = 2019; $i < (int)date('Y'); $i++) {
            self::setKey('previous'.$i);
            self::increase($id, $step);
        }
    }

    public static function flush()
    {
        self::setKey('quarterly');
        Redis::del(static::$key);

        self::setKey('annual');
        Redis::del(static::$key);

        self::setKey('previous');
        Redis::del(static::$key);

        for ($i = 2019; $i < (int)date('Y'); $i++) {
            self::setKey('previous'.$i);
            Redis::del(static::$key);
        }
    }

    public static function refresh()
    {
        static::flush();
        self::multi(function () {
            Rebate::query()
                ->join('users', 'users.id', '=', 'rebates.user_id')
                ->where('rebates.level', 2)
                // ->where('rebates.created_at', '>', now()->startOfYear()->toDateTimeString())
                ->where('users.level', 2)
                ->where('rebates.status', '!=', Rebate::STATUS_FAIL)
                ->orderBy('rebates.id')
                ->select('rebates.*')
                ->each(function ($item) {
                    // self::setKey('annual');
                    // self::increase($item->user_id, $item->money);
                    // if ($item->created_at > now()->startOfQuarter()->toDateTimeString()) {
                    //     self::setKey('quarterly');
                    //     self::increase($item->user_id, $item->money);
                    // }
                    if ($item->created_at > now()->startOfQuarter()->toDateTimeString()) {
                        // 季度
                        self::setKey('quarterly');
                        self::increase($item->user_id, $item->money);
                    }else if ($item->created_at > now()->startOfYear()->toDateTimeString()){
                        //年度
                        self::setKey('annual');
                        self::increase($item->user_id, $item->money);
                    }else if ($item->created_at < now()->startOfYear()->toDateTimeString()) {
                        //往年
                        self::setKey('previous');
                        self::increase($item->user_id, $item->money);

                        //年份
                        for ($i = 2019; $i < (int)date('Y'); $i++) { 
                            if (($item->created_at >= $i . '-01-01 00:00:00') && ($item->created_at <= $i . '-12-31 23:59:59')) {
                                self::setKey('previous'.$i);
                                self::increase($item->user_id, $item->money);
                            }
                        }
                    }
                });
        });
    }

    /**
     * 商家职员排行 - 分页数据
     * @param  int    $offset    [页数]
     * @param  int    $count     [每页条数]
     * @param  string $shop_name [店铺名称]
     * @param  string $interval  [季度:quarterly /年度:annual /往年:previous]
     * @param  string $year      [往年年份]
     * @return array  $re        [key:user_id / value:money]
     */
    public static function shop_ranking($offset = 0, $count = 10, $shop_name = '', $interval = 'quarterly', $year = '')
    {
        $rebate = Rebate::query()
            ->leftjoin('users', 'users.id', '=', 'rebates.user_id')
            ->leftjoin('shops', 'shops.id', '=', 'rebates.shop_id')
            ->where('rebates.level', 2)
            ->where('users.level', 2)
            ->where('rebates.status', '!=', Rebate::STATUS_FAIL)
            ->selectRaw('sum(rebates.money) as total_money,rebates.user_id,shops.name as shop_name')
            ->groupBy('rebates.user_id')
            ->orderBy('total_money', 'desc');

        if ($interval == 'quarterly') {//季度

            $rebate->where('rebates.created_at', '>', now()->startOfQuarter()->toDateTimeString());

        }else if ($interval == 'annual') {//年度

            $rebate->where('rebates.created_at', '>', now()->startOfYear()->toDateTimeString());

        }else if ($interval == 'previous'){//往年

            if ($year) {// 带年份
                $rebate->where('rebates.created_at', '>=', $year . '-01-01 00:00:00');
                $rebate->where('rebates.created_at', '<=', $year . '-12-31 23:59:59');
            }else{// 不带年份
                $rebate->where('rebates.created_at', '<', now()->startOfYear()->toDateTimeString());
            }

        }

        if ($shop_name) {
            $rebate->where('shops.name', 'like', "%".$shop_name."%");
        }

        $data = $rebate
            ->offset($offset)
            ->limit($count)
            ->get();

        $re = [];
        foreach ($data as $key => $value) {
            $re['money_list'][$value->user_id] = (float)$value->total_money;
            $re['shop_list'][$value->user_id] = $value->shop_name;
        }

        return $re;
    }

    /**
     * 商家职员排行 - 全部数据
     * @param  int    $u_id      [用户id]
     * @param  string $shop_name [店铺名字]
     * @param  string $interval  [季度:quarterly /年度:annual /往年:previous]
     * @param  string $year      [往年年份]
     * @return array             [self:自己排名位置/ score:金额/ len:总元素数]
     */
    public static function shop_ranking_all($u_id = 0, $shop_name = '', $interval = 'quarterly', $year = '')
    {
        $rebate = Rebate::query()
            ->leftjoin('users', 'users.id', '=', 'rebates.user_id')
            ->leftjoin('shops', 'shops.id', '=', 'rebates.shop_id')
            ->where('rebates.level', 2)
            ->where('users.level', 2)
            ->where('rebates.status', '!=', Rebate::STATUS_FAIL)
            ->selectRaw('sum(rebates.money) as total_money,rebates.user_id')
            ->groupBy('rebates.user_id')
            ->orderBy('total_money', 'desc');

        if ($interval == 'quarterly') {//季度

            $rebate->where('rebates.created_at', '>', now()->startOfQuarter()->toDateTimeString());

        }else if ($interval == 'annual') {//年度

            $rebate->where('rebates.created_at', '>', now()->startOfYear()->toDateTimeString());

        }else if ($interval == 'previous'){//往年

            if ($year) {// 带年份
                $rebate->where('rebates.created_at', '>=', $year . '-01-01 00:00:00');
                $rebate->where('rebates.created_at', '<=', $year . '-12-31 23:59:59');
            }else{// 不带年份
                $rebate->where('rebates.created_at', '<', now()->startOfYear()->toDateTimeString());
            }
            
        }

        if ($shop_name) {
            $rebate->where('shops.name', 'like', "%".$shop_name."%");
        }

        $data = $rebate->get();

        $aUserId = $money = [];
        foreach ($data as $key => $value) {
            $aUserId[] = $value->user_id;
            $money[$value->user_id] = $value->total_money;
        }

        return [
            'self'  => array_search($u_id, $aUserId),
            'score' => isset($money[$u_id]) ? $money[$u_id] : '',
            'len'   => count($money),
        ];
    }
}
